from PyQt5.QtWidgets import QLabel, QScrollArea, QVBoxLayout, QWidget
from PyQt5.QtCore import Qt, pyqtSignal
from PyQt5.QtGui import QPixmap, QPainter, QPen, QColor, QImage
import numpy as np
import cv2

class ImageViewer(QScrollArea):
    """图像查看器组件"""
    
    def __init__(self):
        super().__init__()
        self._init_ui()

    def _init_ui(self):
        """初始化界面"""
        # 创建图像标签
        self.image_label = QLabel()
        self.image_label.setAlignment(Qt.AlignCenter)
        self.image_label.setStyleSheet("""
            QLabel {
                border: 2px dashed #cccccc;
                border-radius: 8px;
                background-color: #d3d3d3;  /* 设置背景颜色为灰色 */
                color: #999999;
                font-size: 14px;
            }
        """)
        self.image_label.setText("添加图片")
        self.image_label.setMinimumSize(400, 300)

        # 设置滚动区域属性
        self.setWidget(self.image_label)
        self.setWidgetResizable(True)
        self.setAlignment(Qt.AlignCenter)
    
    def display_image(self, image: np.ndarray):
        """显示图像"""
        if image is None:
            self.clear_image()
            return
            
        try:
            # 确保图像是RGB格式的numpy数组
            if len(image.shape) == 3:
                height, width, channel = image.shape
                # 确保是RGB格式
                if channel == 3:
                    # numpy数组转换为QImage
                    bytes_per_line = 3 * width
                    q_image = QImage(image.data, width, height, bytes_per_line, QImage.Format_RGB888)
                else:
                    raise ValueError("不支持的图像通道数")
            else:
                raise ValueError("图像格式不正确")
            
            # QImage转换为QPixmap
            pixmap = QPixmap.fromImage(q_image)
            
            # 获取当前显示区域大小
            display_size = self.viewport().size()
            
            # 缩放图像以适应显示区域，保持宽高比
            if pixmap.width() > display_size.width() - 20 or pixmap.height() > display_size.height() - 20:
                scaled_pixmap = pixmap.scaled(
                    display_size.width() - 20, 
                    display_size.height() - 20,
                    Qt.KeepAspectRatio, 
                    Qt.SmoothTransformation
                )
            else:
                scaled_pixmap = pixmap
            
            # 设置到标签
            self.image_label.setPixmap(scaled_pixmap)
            self.image_label.resize(scaled_pixmap.size())
            
        except Exception as e:
            print(f"显示图像时出错: {e}")
            self.clear_image()
    
    def clear_image(self):
        """清空图像显示"""
        self.image_label.clear()
        self.image_label.setText("请选择图像文件")
        self.image_label.setMinimumSize(400, 300)
    
    def resizeEvent(self, event):
        """窗口大小改变事件"""
        super().resizeEvent(event)
        # 如果有图像，可以在这里重新缩放
        if hasattr(self, 'original_pixmap') and self.original_pixmap:
            # 重新缩放逻辑可以在这里实现
            pass
